/**
 * 
 */
package com.flashdeck.dao.impl;

import java.io.File;

import android.content.SharedPreferences;
import android.os.Environment;

import com.flashdeck.dao.SettingsDao;

/**
 * @author Vincentas
 *
 */
public class SettingsDaoImpl implements SettingsDao {

	private static final String DECK_FOLDER = "decksPath";
	
	private static final String REMOTE_REPOSITORY = "remoteRepository";
	
	private static SettingsDaoImpl instance = null;
	
	private SharedPreferences preferences = null;
	
	public synchronized static SettingsDao getInstance() {
		if (instance == null) {
			instance = new SettingsDaoImpl();
		}
		
		return instance;
	}
	
	/**
	 * @return the preference
	 */
	public SharedPreferences getPreferences() {
		return preferences;
	}
	
	/**
	 * @param preference the preference to set
	 */
	public void setPreferences(SharedPreferences preferences) {
		this.preferences = preferences;
	}

	@Override
	public File getDeckFolder() {
		File externalStorageDirectory = Environment.getExternalStorageDirectory();
		
		String folderPath = getPreferences().getString(DECK_FOLDER, "/decks");
		
		File result = new File(externalStorageDirectory.getAbsoluteFile() + folderPath);
		if (result.exists()) {
			if (result.isFile()) {
				throw new Error("Deck folder is invalid (file) " + result.getAbsolutePath());
			}
		} else {
			boolean created = result.mkdirs();
			if (!created) {
				throw new Error("Unable to create folder " + result.getAbsolutePath());
			}
		}
		
		return result;
	}

	@Override
	public String getRemoteRepository() {
		return getPreferences().getString(REMOTE_REPOSITORY, "http://www.flashdecks.com");
	}
	
	


}
